package com.wy.panda.common.http;

import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.session.web.http.HttpSessionIdResolver;

import com.wy.panda.common.util.CollectionUtils;
import com.wy.panda.common.util.StringUtils;

/**
 * 自定义sessionId在请求中存储方式：header方式或者parameter方式请求传递存放
 * 优先顺序：手续考虑header方式，其次考虑parameter方式
 * @author wangyuan
 * @since 2020年2月3日 下午12:01:12
 *
 */
public class PandaHttpSessionIdResolver implements HttpSessionIdResolver {
	
	public static final String HEADER_X_AUTH_TOKEN = "X-Auth-Token";
	
	public static final String PARAMETER_TOKEN = "token";
	
	public static PandaHttpSessionIdResolver instance() {
		return new PandaHttpSessionIdResolver();
	}

	@Override
	public List<String> resolveSessionIds(HttpServletRequest request) {
		String headerValue = request.getHeader(HEADER_X_AUTH_TOKEN);
		List<String> result = StringUtils.isNotBlank(headerValue) ? Collections.singletonList(headerValue) : Collections.emptyList();
		if(CollectionUtils.isNotEmpty(result)) {
			return result;
		}
		
		String parameterValue = request.getParameter(PARAMETER_TOKEN);
		result = StringUtils.isNotBlank(parameterValue) ? Collections.singletonList(parameterValue) : Collections.emptyList();
		
		return result;
	}

	@Override
	public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
	    response.setHeader(HEADER_X_AUTH_TOKEN, sessionId);
	}

	@Override
	public void expireSession(HttpServletRequest request, HttpServletResponse response) {
	    response.setHeader(HEADER_X_AUTH_TOKEN, "");
	}

}
